package controllers

import (
	"acs/management/models"
	"acs/taskprocess"
	"fmt"
	"net/http"
	"regexp"
	"strconv"
	"time"

	"github.com/labstack/echo"
	msgpack "gopkg.in/vmihailenco/msgpack.v2"
)

type v2UpvEventForm struct {
	UIDs     []string `json:"uids"`
	Content  string   `json:"content"`
	TaskID   string   `json:"taskid"`
	Callback string   `json:"callback"`
}

// V2UpvEvent 通过上传包含用户更新app补丁的数组txt
func V2UpvEvent(c echo.Context) error {
	defer models.ErrorHandler(c)

	var form v2UpvEventForm
	if e := c.Bind(&form); e != nil {
		return c.JSON(http.StatusBadRequest, "http body must be json")
	} else if len(form.UIDs) == 0 {
		return c.JSON(http.StatusBadRequest, "uids is empty")
	}

	var useridList []string
	checkMap := map[string]bool{}
	if len(form.UIDs) > 0 && form.UIDs[0] == "*" {
		useridList = []string{"*"}
	} else {
		for _, useridstr := range form.UIDs {
			matched, matcherr := regexp.Match(models.Conf.NsqUpv.Nsq_upv_uid_regexp, []byte(useridstr))
			if matcherr != nil {
				return c.JSON(http.StatusBadRequest, "uid error: "+matcherr.Error())
			}
			if matched == false {
				return c.JSON(http.StatusBadRequest, "上传文件uid文件格式不符合!")

			}
			if _, ok := checkMap[useridstr]; !ok {
				checkMap[useridstr] = true
				useridList = append(useridList, useridstr)
			}
		}
	}

	var lable = "EventLable"
	eventTask := &taskprocess.EventTask{}
	eventTask.TargetUID = useridList
	eventTask.Content = &form.Content
	eventTask.Label = &lable

	eventTask.TaskID = form.TaskID
	eventTask.Callback = form.Callback

	//过滤条件
	eventTask.Appver = [2]string{"*", "*"}
	eventTask.OSVersion = [2]string{"*", "*"}

	rb, schemaerr := msgpack.Marshal(eventTask)
	if schemaerr != nil {
		return c.JSON(http.StatusServiceUnavailable, "eventTask:"+schemaerr.Error())
	}
	taskProtoNew := taskprocess.TaskInQueue{}
	taskProtoNew.Type = taskprocess.TaskTypeEvent

	taskProtoNew.RawBytes = rb
	tb, tberr := msgpack.Marshal(taskProtoNew)
	if tberr != nil {
		return c.JSON(http.StatusServiceUnavailable, "taskProtoNew:"+tberr.Error())
	}
	nsqerr := models.PushUPV2NSQ(tb)
	if nsqerr != nil {
		return c.JSON(http.StatusServiceUnavailable, "tb:"+nsqerr.Error())
	}

	fmt.Printf("{\"time\": \"%v\", \"msg\":\"PushEvent\", \"from\": \"%v\", \"data\": \"%v\"}\n",
		time.Now().Format("2006-01-02 15:04:05"),
		c.Request().RemoteAddr,
		form)
	return c.JSON(http.StatusOK, "主动推送Event:"+*eventTask.Content+"的成功数目为:"+strconv.Itoa(len(useridList)))
}
